package com.eiei.db.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.eiei.common.CommonValue;

/**
 * 数据库连接池，单例模式
 * @author eiei
 *
 */
public class ConnectionPool {
	
	private static final Logger logger = Logger.getLogger(ConnectionPool.class);

	private static int defalt_pool_size = 2;
	
	private static List<Connection> pools ;
	
	static{
		pools = new ArrayList<Connection>();
		try {
			for(int i = 0;i<defalt_pool_size;i++){
				pools.add(createConnection());
			}
		} catch (Exception e) {
			logger.error(e);
		}
//		logger.info("初始化数据库连接池成功。");
	}
	
	private ConnectionPool() {
	}
	
	/**
	 * 创建数据库连接
	 * @return
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	private static Connection createConnection() throws Exception{
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection(CommonValue.DB_MAP.get("db.url"),
				CommonValue.DB_MAP.get("db.username"),CommonValue.DB_MAP.get("db.password"));
		con.setAutoCommit(false);
		return con;
	}
	
	/**
	 * 获取数据库连接
	 * @return
	 * @throws Exception 
	 */
	public static Connection getConnection() throws Exception{
		synchronized (pools) {
			if(pools.size()>0){
				Connection con = pools.get(0);
				pools.remove(0);
				return con;
			}else{
				return createConnection();
			}
		}
	}
	
	/**
	 * 释放数据库连接，返回连接池，或者断开连接
	 * @param con
	 * @throws Exception 
	 */
	public static void freeConection(Connection con) throws Exception{
		if(con != null){
			synchronized (pools) {
				if(pools.size()<defalt_pool_size){
					pools.add(con);
				}else{
					if(!con.isClosed()){
						con.close();
					}
				}
			}
		}
		con = null;
		
	}
	
}
